package com.tobeface.sns.infrastructure.persist.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.kissme.lang.Preconditions;
import com.tobeface.sns.domain.User;
import com.tobeface.sns.domain.UserRepository;
import com.tobeface.sns.infrastructure.persist.CrudMongoRepositorySupport;

/**
 * 
 * @author loudyn
 * 
 */
@Repository
public class MongoUserRepository extends CrudMongoRepositorySupport<User, String> implements UserRepository {

	/**
	 * 
	 * @param mongoOperations
	 */
	@Autowired
	public MongoUserRepository(MongoOperations mongoOperations) {
		super(mongoOperations);
	}

	@Override
	public User queryUniqueByUsername(String username) {
		return getMongoOperations().findOne(new Query(Criteria.where("member.username").is(username)), getEntityInformation().getJavaType());
	}

	@Override
	public boolean existsByUsernameAndEmail(String username, String email) {

		return null != getMongoOperations().findOne(
														new Query(Criteria.where("username").is(username).and("email").is(email)),
														getEntityInformation().getJavaType()
												);
	}

	@Override
	public boolean existsByUsernameOrEmail(String username) {
		return null != getMongoOperations().findOne(
														new Query(Criteria.where("username").is(username)),
														getEntityInformation().getJavaType()
												);
	}

	@Override
	public void updatePassword(String username, String newPassword) {

		
		getMongoOperations().updateFirst(
											new Query(Criteria.where("username").is(username)), 
											Update.update("password", newPassword),
											getEntityInformation().getJavaType()
									);
	}

	@Override
	public User queryUniqueByEmail(String email) {
		return getMongoOperations().findOne(new Query(Criteria.where("email").is(email)), getEntityInformation().getJavaType());
	}

	@Override
	public void updateEmail(String username, String newEmail) {
		getMongoOperations().updateFirst(
											new Query(Criteria.where("username").is(username)), Update.update("email", newEmail),
											getEntityInformation().getJavaType()
									);
	}
	
	@Override
	public User save(User user) {
		Preconditions.notNull(user.getMember(), "Entity must not be null!");
		getMongoOperations().save(user.getMember(), "member");
		return super.save(user);
	}

}
